package com.medica.ledproject.socke;

/**
 * @author xiaona
 * @date 2024/5/30
 * @description TODO
 */

import com.medica.ledproject.LedProjectApplication;
import com.medica.ledproject.led.HexUtil;
import com.medica.ledproject.service.IDzParkZhaService;
import com.medica.ledproject.service.impl.DzParkZhaServiceImpl;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetSocketAddress;

public class SocketHandler extends ChannelInboundHandlerAdapter
{
    @Autowired
    IDzParkZhaService dzParkZhaService;
    private static final Logger log = LoggerFactory.getLogger(SocketHandler.class);

    public static final ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception
    {
        byte[] data = (byte[])(byte[])msg;
        System.out.println(ctx.channel().id().asShortText()+"server channelRead......");
        System.out.println("----->Server :" + HrsUtil.bytesToHexString(data) );
        //需要把状态写入数据库中
        String clientIp = ((InetSocketAddress) ctx.channel().remoteAddress()).getHostString();
        String dstas= HexUtil.bytes2HexString(data);
        DzParkZhaServiceImpl dzParkZhaService = LedProjectApplication.getBean(DzParkZhaServiceImpl.class);
        dzParkZhaService.updateZha(dstas,clientIp);
        for (Channel client : clients) {
            System.err.println("进来了111");
            if (client.equals(ctx.channel()))
                System.err.println("进来了");
        }
    }

    public void handlerAdded(ChannelHandlerContext ctx)
            throws Exception
    {
        log.info("新的客户端链接：" + ctx.channel().id().asShortText());
        String clientIp = ((InetSocketAddress) ctx.channel().remoteAddress()).getHostString();
        System.out.println("Client IP: " + clientIp);
        clients.add(ctx.channel());
    }

    public void handlerRemoved(ChannelHandlerContext ctx)
            throws Exception
    {
        System.err.println("删除");
        clients.remove(ctx.channel());
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        System.err.println("删除：exceptionCaught");
        cause.printStackTrace();
        ctx.channel().close();
        clients.remove(ctx.channel());
    }
}